/**
 * @author yxw
 * date : 2013年11月3日 下午4:57:39 
 */
package com.tzinfo.tzt.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.galhttprequest.GalHttpRequest.GalHttpLoadTextCallBack;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tzinfo.data.TztData;
import com.tzinfo.data.UserInfo;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.view.FabuPickViewPopupWindow;
import com.tzinfo.tzt.activity.view.MyProgressDialog;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.config.FileConfig;
import com.tzinfo.tzt.domain.HousePubPara;
import com.tzinfo.tzt.domain.MyResultList;
import com.tzinfo.tzt.domain.OldhousePubDetail;
import com.tzinfo.tzt.domain.OldhousePubDetail.Pics;
import com.tzinfo.tzt.domain.RenthousePubDetail;
import com.tzinfo.tzt.util.FileTools;
import com.tzinfo.tzt.util.HttpTools;
import com.tzinfo.tzt.util.JsonTools;
import com.umeng.update.UmengUpdateAgent;

public class MyFabuUpdateActivity extends BaseActivity implements
		OnCheckedChangeListener {

	// UI组件
	public TextView text_type, text_floor, text_direction, text_areaqy,
			text_community, text_communityid, text_houseid;
	private TextView text_priceUnit, text_housetype, text_title, text_price;
	private EditText et_title, et_address, et_price, et_area, et_description,
			et_agent_name, et_agent_tel;
	private ImageView addpicImage;
	private LinearLayout images_layout;
	private Button bt_save;
	private LinearLayout layout_bt_delete;

	// 其他
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	private Dialog dialog;
	private AlertDialog dlg;
	private RadioGroup radiogroup;
	FabuPickViewPopupWindow popupWindow;

	// 数据
	private HousePubPara housePubPara;
	private MyResultList resultList;
	private List<Object> imageList;

	// 标志
	private boolean isOld = true;
	private boolean isPub = true;
	private String houseId = "0";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_my_fabu_update);
		isPub = this.getIntent().getBooleanExtra("isPub", true);
		isOld = this.getIntent().getBooleanExtra("isOld", true);
		houseId = this.getIntent().getStringExtra("houseId");
		housePubPara = new HousePubPara();
		init();
		loadHousePara();
	}

	private void init() {

		UmengUpdateAgent.setUpdateOnlyWifi(false);
		UmengUpdateAgent.update(this);
		UmengUpdateAgent.setUpdateAutoPopup(true);
		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.ic_empty)
				.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
				.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
		dialog = new MyProgressDialog(this).createDialog(getResources()
				.getString(R.string.loading));
		addpicImage = (ImageView) this.findViewById(R.id.addpic);
		images_layout = (LinearLayout) this.findViewById(R.id.images_layout);
		text_price = (TextView) this.findViewById(R.id.text_price);
		if (!isOld) {
			text_price.setText("租金：");
		}
		text_title = (TextView) this.findViewById(R.id.text_title);
		if (!isPub) {
			text_title.setText("修改房源");
		}
		text_housetype = (TextView) this.findViewById(R.id.text_housetype);
		text_priceUnit = (TextView) this.findViewById(R.id.text_priceUnit);
		text_houseid = (TextView) this.findViewById(R.id.text_houseid);
		text_type = (TextView) this.findViewById(R.id.text_type);
		text_floor = (TextView) this.findViewById(R.id.text_floor);
		text_direction = (TextView) this.findViewById(R.id.text_direction);
		text_areaqy = (TextView) this.findViewById(R.id.text_areaqy);
		text_community = (TextView) this.findViewById(R.id.text_community);
		text_communityid = (TextView) this.findViewById(R.id.text_communityid);
		et_title = (EditText) this.findViewById(R.id.et_title);
		et_address = (EditText) this.findViewById(R.id.et_address);
		et_price = (EditText) this.findViewById(R.id.et_price);
		et_area = (EditText) this.findViewById(R.id.et_area);
		et_description = (EditText) this.findViewById(R.id.et_description);
		et_agent_name = (EditText) this.findViewById(R.id.et_agent_name);
		et_agent_tel = (EditText) this.findViewById(R.id.et_agent_tel);
		layout_bt_delete = (LinearLayout) this
				.findViewById(R.id.layout_bt_delete);
		bt_save = (Button) this.findViewById(R.id.bt_save);
		radiogroup = (RadioGroup) this.findViewById(R.id.radiogroup);
		radiogroup.setOnCheckedChangeListener(this);
	}

	// onclick
	public void submitInfo(View v) {
		GalHttpRequest galHttpRequest = new GalHttpRequest(this);
		galHttpRequest.setCacheEnable(false);
		String url = getUrl();
		if (url != null) {
			dialog.show();
			galHttpRequest.setURL(url);
			galHttpRequest
					.startAsynRequestString(new GalHttpLoadTextCallBack() {

						@Override
						public void textLoaded(String arg0) {
							resultList = JsonTools.getResult(arg0);
							if (resultList.getSuccess()) {
								String msg;
								if (isPub) {
									houseId = (String) resultList
											.getErrorMessage();
									msg = "恭喜，创建房源信息成功！";
								} else {
									msg = "修改房源信息成功！";
								}
								Toast.makeText(MyFabuUpdateActivity.this, msg,
										Toast.LENGTH_SHORT).show();
								Toast.makeText(MyFabuUpdateActivity.this,
										"开始上传房源图片!", Toast.LENGTH_LONG).show();
								new Thread(upLoadImageRun).start();
							} else {
								Toast.makeText(MyFabuUpdateActivity.this,
										resultList.getErrorMessage(),
										Toast.LENGTH_SHORT).show();
								dialog.dismiss();
							}
						}
					});
		}

	}

	// 根据标志 获取请求url
	private String getUrl() {
		// 获取需要上传的参数，必须在获取url之前
		String error = getHouseInfo();
		if (error == null) {
			String url = null;
			if (isOld) {
				if (isPub) {
					url = housePubPara.getOldPubUrl(AppDataConfig.fabuUrl
							+ AppDataConfig.OldhousePub);
				} else {
					url = housePubPara.getOldUpdateUrl(AppDataConfig.fabuUrl
							+ AppDataConfig.OldhouseUpdate);
				}
			} else {
				if (isPub) {
					url = housePubPara.getRentPubUrl(AppDataConfig.fabuUrl
							+ AppDataConfig.RenthousePub);
				} else {
					url = housePubPara.getRentUpdateUrl(AppDataConfig.fabuUrl
							+ AppDataConfig.RenthouseUpdate);
				}
			}
			Log.e("url", url);
			return url;
		} else {
			Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
			return null;
		}
	}

	// 得到控件上的信息到bean
	private String getHouseInfo() {
		String sTitle = et_title.getText().toString();
		if ("".equals(sTitle)) {
			return "请填写标题";
		}
		housePubPara.setTitle(sTitle);

		String sAddress = et_address.getText().toString();
		if ("".equals(sAddress)) {
			return "请填写房源地址";
		}
		housePubPara.setAddress(sAddress);

		// 价格
		String price = et_price.getText().toString();
		if ("".equals(price)) {
			return "请填写房源价格";
		}
		housePubPara.setPrice("".equals(price) ? 0 : Integer.parseInt(price));

		String sType = text_type.getText().toString();
		if ("".equals(sType)) {
			return "请选择房源类型";
		}
		housePubPara.setType(sType);

		// 面积
		String area = et_area.getText().toString();
		if ("".equals(area)) {
			return "请填写房源面积";
		}
		housePubPara.setArea("".equals(area) ? 0 : Integer.parseInt(area));

		// 楼层
		String floor = text_floor.getText().toString();
		if ("".equals(floor)) {
			return "请选择楼层";
		}
		if (floor != null && !"".equals(floor)) {
			String[] floors = floor.split("/");
			housePubPara.setAllFloor(Integer.parseInt(floors[1]));
			housePubPara.setCurrentFloor(Integer.parseInt(floors[0]));
		} else {
			housePubPara.setAllFloor(0);
			housePubPara.setCurrentFloor(0);
		}

		housePubPara.setDescription(et_description.getText().toString());

		String sDirection = text_direction.getText().toString();
		if ("".equals(sDirection)) {
			return "请选择选择房源朝向";
		}
		housePubPara.setOrientations(sDirection);

		String sAreaqy = text_areaqy.getText().toString();
		if ("".equals(sAreaqy)) {
			return "请选择房源区域";
		}
		housePubPara.setAreaqy(sAreaqy);

		// 小区id
		String communityID = text_communityid.getText().toString();
		if ("".equals(communityID)) {
			return "请选择小区";
		}
		housePubPara.setCommunityID("".equals(communityID) ? 0 : Integer
				.parseInt(communityID));
		String sAgent_name = et_agent_name.getText().toString();
		if ("".equals(sAgent_name)) {
			return "请填写姓名";
		}
		housePubPara.setPubName(sAgent_name);

		String sAgent_tel = et_agent_tel.getText().toString();
		if ("".equals(sAgent_tel)) {
			return "请填写联系方式";
		}
		housePubPara.setPubPhone(sAgent_tel);

		// sessionid
		UserInfo user = TztData.userInfo;
		housePubPara.setSessionid(user != null ? user.getData().getSessionID() : "");

		// 房源id,修改时用到
		String houseId = text_houseid.getText().toString();
		housePubPara.setHouseId("".equals(houseId) ? 0 : Integer
				.parseInt(houseId));

		return null;
	}

	private void loadHousePara() {
		imageList = new ArrayList<Object>();
		if (!isPub) {
			dialog.show();
			GalHttpRequest galHttpRequest = new GalHttpRequest(this);
			galHttpRequest.setCacheEnable(false);
			String url;
			if (isOld) {
				url = AppDataConfig.fabuUrl + AppDataConfig.OldhousePubDetail
						+ "?id=" + houseId;
				text_housetype.setText("二手房");
				text_priceUnit.setText("万");

			} else {
				url = AppDataConfig.fabuUrl + AppDataConfig.RenthousePubDetail
						+ "?id=" + houseId;
				text_housetype.setText("租房");
				text_priceUnit.setText("元/月");
			}
			text_housetype.setVisibility(View.VISIBLE);
			layout_bt_delete.setVisibility(View.VISIBLE);
			bt_save.setText("修改");
			Log.e("url", url);
			galHttpRequest.setURL(url);
			galHttpRequest
					.startAsynRequestString(new GalHttpLoadTextCallBack() {

						@Override
						public void textLoaded(String arg0) {
							setHousePara(arg0);
							dialog.dismiss();
						}
					});
		}
	}

	private void setHousePara(String jsonString) {
		if (isOld) {
			OldhousePubDetail house = (OldhousePubDetail) JsonTools
					.getOldhousePubDetail(jsonString);
			if (house.isSuccess()) {
				int imgSize = house.getPics().size();
				imgSize = imgSize > 4 ? 4 : imgSize;
				for (int i = 0; i < imgSize; i++) {
					imageList.add(house.getPics().get(i));
					LinearLayout item_view = (LinearLayout) getLayoutInflater()
							.inflate(R.layout.item_upload_image, null);
					ImageView uploadImg = (ImageView) item_view
							.findViewById(R.id.uploadImg);
					ImageView deleteImg = (ImageView) item_view
							.findViewById(R.id.uploadImg_delete);
					deleteImg
							.setOnClickListener(new OnImageDeleteClickListener(
									house.getPics().get(i), item_view));
					images_layout.addView(item_view, i);
					imageLoader.displayImage(house.getPics().get(i).getUrl(),
							uploadImg, options);
				}
				if (imgSize == 4) {
					addpicImage.setVisibility(View.GONE);
				}
				// 填充数据
				text_houseid.setText(house.getID() + "");
				text_type.setText(house.getType());
				text_floor.setText(house.getCurrentFloor() + "/"
						+ house.getAllFloor());
				text_direction.setText(house.getOrientations());
				text_areaqy.setText(house.getAreaqy());
				text_community.setText(house.getCommunityName());
				text_communityid.setText(house.getCommunityID() + "");
				et_title.setText(house.getTitle());
				et_address.setText(house.getAddress());
				et_price.setText(house.getTotalP() + "");
				et_area.setText(house.getArea() + "");
				et_description.setText(house.getDescription());
				et_agent_name.setText(house.getPubName());
				et_agent_tel.setText(house.getPubPhone());
			} else {
				Toast.makeText(this, "网络异常！", Toast.LENGTH_SHORT).show();
				this.finish();
			}
		} else {
			RenthousePubDetail house = (RenthousePubDetail) JsonTools
					.getRenthousePubDetail(jsonString);
			if (house.isSuccess()) {
				int imgSize = house.getPics().size();
				imgSize = imgSize > 4 ? 4 : imgSize;
				for (int i = 0; i < imgSize; i++) {
					imageList.add(house.getPics().get(i));
					LinearLayout item_view = (LinearLayout) getLayoutInflater()
							.inflate(R.layout.item_upload_image, null);
					ImageView uploadImg = (ImageView) item_view
							.findViewById(R.id.uploadImg);
					ImageView deleteImg = (ImageView) item_view
							.findViewById(R.id.uploadImg_delete);
					deleteImg
							.setOnClickListener(new OnImageDeleteClickListener(
									house.getPics().get(i), item_view));
					images_layout.addView(item_view, i);
					imageLoader.displayImage(house.getPics().get(i).getUrl(),
							uploadImg, options);
				}
				if (imgSize == 4) {
					addpicImage.setVisibility(View.GONE);
				}
				text_houseid.setText(house.getID() + "");
				text_type.setText(house.getType());
				text_floor.setText(house.getCurrentFloor() + "/"
						+ house.getAllFloor());
				text_direction.setText(house.getOrientations());
				text_areaqy.setText(house.getAreaqy());
				text_community.setText(house.getCommunityName());
				text_communityid.setText(house.getCommunityID() + "");
				et_title.setText(house.getTitle());
				et_address.setText(house.getAddress());
				et_price.setText(house.getReprises() + "");
				et_area.setText(house.getArea() + "");
				et_description.setText(house.getDescription());
				et_agent_name.setText(house.getPubName());
				et_agent_tel.setText(house.getPubPhone());
			} else {
				Toast.makeText(this, "网络异常！", Toast.LENGTH_SHORT).show();
				this.finish();
			}
		}
	}

	// onclick
	public void deleteHouse(View v) {
		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage("确认删除该房源吗？")
				.setPositiveButton(getResources().getString

				(R.string.cancel), new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
					}
				}).setNegativeButton(getResources().getString

				(R.string.sure), new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
						doDeleteHouse();
					}
				}).show();
	}

	private void doDeleteHouse() {
		dialog.show();
		GalHttpRequest galHttpRequest = new GalHttpRequest(this);
		galHttpRequest.setCacheEnable(false);
		String url = AppDataConfig.fabuUrl + AppDataConfig.HouseDelete;
		url += "?HouseID=" + houseId + "&sessionid="
				+ TztData.userInfo.getData().getSessionID();
		Log.e("url", url);
		galHttpRequest.setURL(url);
		galHttpRequest.startAsynRequestString(new GalHttpLoadTextCallBack() {

			@Override
			public void textLoaded(String s) {
				MyResultList result = JsonTools.getResult(s);
				if (result.getSuccess()) {
					Toast.makeText(MyFabuUpdateActivity.this, "房源删除成功！",
							Toast.LENGTH_SHORT).show();
					MyFabuUpdateActivity.this.finish();
				} else {
					Toast.makeText(MyFabuUpdateActivity.this,
							result.getErrorMessage(), Toast.LENGTH_SHORT)
							.show();
				}
				dialog.dismiss();
			}
		});
	}

	// onclick
	public void showType(View v) {
		popupWindow = new FabuPickViewPopupWindow(this);
		popupWindow.showTypePick();
		popupWindow.showAtLocation(this.findViewById(R.id.main), Gravity.BOTTOM
				| Gravity.CENTER_HORIZONTAL, 0, 0);
	}

	// onclick
	public void showDirection(View v) {
		popupWindow = new FabuPickViewPopupWindow(this);
		popupWindow.showDirectionPick();
		popupWindow.showAtLocation(this.findViewById(R.id.main), Gravity.BOTTOM
				| Gravity.CENTER_HORIZONTAL, 0, 0);
	}

	// onclick
	public void showAreaqy(View v) {
		popupWindow = new FabuPickViewPopupWindow(this);
		popupWindow.showAreaqyPick();
		popupWindow.showAtLocation(this.findViewById(R.id.main), Gravity.BOTTOM
				| Gravity.CENTER_HORIZONTAL, 0, 0);
	}

	// onclick
	public void showFloor(View v) {
		popupWindow = new FabuPickViewPopupWindow(this);
		popupWindow.showFloorPick();
		popupWindow.showAtLocation(this.findViewById(R.id.main), Gravity.BOTTOM
				| Gravity.CENTER_HORIZONTAL, 0, 0);
	}

	// onclick
	public void showSelectCommunity(View v) {
		Intent intent = new Intent(this, MyFabuSearchCommunityActivity.class);
		startActivityForResult(intent, 1);
	}

	Runnable upLoadImageRun = new Runnable() {

		@Override
		public void run() {
			Message message = handler.obtainMessage();
			String url = AppDataConfig.fabuUrl + AppDataConfig.housePicPub
					+ "?HouseID=" + houseId + "&sessionid="
					+ TztData.userInfo.getData().getSessionID();
			Log.e("url", url);
			String path = null;
			while (imageList.size() > 0) {
				Object obj = imageList.get(0);
				if (obj instanceof String) {
					path = (String) obj;
					break;
				}
				imageList.remove(obj);
			}
			if (path != null) {
				String jsonString = HttpTools.uploadImage(url, path);
				Log.e("jsonImage", jsonString);
				MyResultList result = JsonTools.getResult(jsonString);
				if (!result.getSuccess()) {
					message.arg1 = -1;
				} else {
					imageList.remove(path);
				}
			}
			message.arg1 = 1;
			handler.sendMessage(message);
		}
	};
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case 1:
				if (imageList.size() == 0) {
					dialog.dismiss();
					Toast.makeText(MyFabuUpdateActivity.this, "发布房源成功！",
							Toast.LENGTH_SHORT).show();
					MyFabuUpdateActivity.this.finish();
				} else {
					Toast.makeText(MyFabuUpdateActivity.this, "正在上传图片请稍候…",
							Toast.LENGTH_LONG).show();
					new Thread(upLoadImageRun).start();
				}
				break;
			case -1:
				dialog.dismiss();
				Toast.makeText(MyFabuUpdateActivity.this, "房源图片上传失败！",
						Toast.LENGTH_SHORT).show();
				MyFabuUpdateActivity.this.finish();
				break;
			}
		}
	};

	// 显示选择相册or照片
	public void showAddImageDialog(View v) {
		final CharSequence[] items = { "相册", "拍照", "取消" };

		dlg = new AlertDialog.Builder(this).setTitle("选择照片")
				.setItems(items, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						// 这里item是根据选择的方式， 在items数组里面定义了两种方式，拍照的下标为1所以就调用拍照方法
						if (which == 0) {
							Intent getImage = new Intent(
									Intent.ACTION_GET_CONTENT);
							getImage.addCategory(Intent.CATEGORY_OPENABLE);
							getImage.setType("image/jpeg");
							startActivityForResult(getImage, 2);
						} else if (which == 1) {
							Intent getImageByCamera = new Intent(
									"android.media.action.IMAGE_CAPTURE");
							File tempFile = new File(FileConfig.IMAGE_PATH);
							if (!tempFile.isDirectory()) {
								tempFile.mkdirs();
							}
							FileConfig.IMAGE_NAME = FileConfig
									.getRandomJpgName();
							Uri imageUri = Uri.fromFile(new File(
									FileConfig.IMAGE_PATH,
									FileConfig.IMAGE_NAME));
							// 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
							getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT,
									imageUri);
							startActivityForResult(getImageByCamera, 3);
						} else {
							dlg.dismiss();
						}

					}
				}).create();
		dlg.show();
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.oldRadio:
			isOld = true;
			text_priceUnit.setText("万");
			break;
		default:
			text_priceUnit.setText("元/月");
			isOld = false;
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		BitmapFactory.Options option = null;
		Bitmap bitmap = null;
		switch (requestCode) {
		case 1:
			if (resultCode == 1) {
				text_communityid.setText(data.getStringExtra("communityId"));
				text_community.setText(data.getStringExtra("community"));
			}
			break;
		case 2:
			if (data != null) {
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };

				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				cursor.close();
				// 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
				option = new BitmapFactory.Options();
				bitmap = BitmapFactory.decodeFile(picturePath);
				option.inSampleSize = FileTools.getInSampleSize(bitmap);
				bitmap.recycle();
				imageList.add(picturePath);
				addImagelayout(BitmapFactory.decodeFile(picturePath, option),
						picturePath);
			}
			break;
		case 3:
			// 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
			option = new BitmapFactory.Options();
			String path = FileConfig.IMAGE_PATH + "/" + FileConfig.IMAGE_NAME;
			imageList.add(path);
			bitmap = BitmapFactory.decodeFile(path);
			option.inSampleSize = FileTools.getInSampleSize(bitmap);
			bitmap.recycle();
			addImagelayout(BitmapFactory.decodeFile(path, option), path);
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void addImagelayout(Bitmap decodeFile, String path) {
		LinearLayout item_view = (LinearLayout) getLayoutInflater().inflate(
				R.layout.item_upload_image, null);
		ImageView uploadImg = (ImageView) item_view
				.findViewById(R.id.uploadImg);
		ImageView deleteImg = (ImageView) item_view
				.findViewById(R.id.uploadImg_delete);
		deleteImg.setOnClickListener(new OnImageDeleteClickListener(path,
				item_view));
		uploadImg.setImageBitmap(decodeFile);
		images_layout.addView(item_view, imageList.size() - 1);
		if (imageList.size() == 4) {
			addpicImage.setVisibility(View.GONE);
		}

	}

	class OnImageDeleteClickListener implements OnClickListener {
		Object object;
		View view;

		public OnImageDeleteClickListener(Object object, View view) {
			this.object = object;
			this.view = view;
		}

		@Override
		public void onClick(View v) {
			new AlertDialog.Builder(MyFabuUpdateActivity.this)
					.setTitle(getResources().getString(R.string.tips))
					.setMessage("您确定要删除这张照片吗？")
					.setPositiveButton("确	定",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									deleteImage();
								}
							})
					.setNegativeButton("取	消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
								}
							}).show();
		}

		private void deleteImage() {
			dialog.show();
			if (object instanceof Pics) {// 网络的删除需要通过HTTP请求
				Pics pics = (Pics) object;
				GalHttpRequest galHttpRequest = new GalHttpRequest(
						MyFabuUpdateActivity.this);
				String url = AppDataConfig.fabuUrl
						+ AppDataConfig.HousePicDelete + "?PicId="
						+ pics.getPicID() + "&sessionid="
						+ TztData.userInfo.getData().getSessionID();
				Log.e("url", url);
				galHttpRequest.setURL(url);
				galHttpRequest
						.startAsynRequestString(new GalHttpLoadTextCallBack() {

							@Override
							public void textLoaded(String arg0) {
								MyResultList result = JsonTools.getResult(arg0);
								if (result.getSuccess()) {
									images_layout.removeView(view);
									imageList.remove(object);
									if (imageList.size() < 4) {
										addpicImage.setVisibility(View.VISIBLE);
									}
									Toast.makeText(MyFabuUpdateActivity.this,
											"已删除图片！", 3000).show();
								} else {
									Toast.makeText(MyFabuUpdateActivity.this,
											result.getErrorMessage(), 3000)
											.show();
								}
								dialog.dismiss();
							}
						});

			} else {// 否则只需要删除图片即可
				images_layout.removeView(view);
				imageList.remove(object);
				if (imageList.size() < 4) {
					addpicImage.setVisibility(View.VISIBLE);
				}
				Toast.makeText(MyFabuUpdateActivity.this, "已删除图片！", 3000)
						.show();
				dialog.dismiss();
			}

		}
	}
}
